package net.showcal.home.module.screen.api;

import com.alibaba.citrus.service.requestcontext.buffered.BufferedRequestContext;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.alibaba.fastjson.JSON;
import com.showcal.foundation.domain.UploadTypeEnum;
import com.showcal.foundation.request.FoodFileUploadRequest;
import com.showcal.foundation.service.FoundationService;
import com.xiniunet.framework.base.BaseResponse;
import com.xiniunet.framework.exception.ErrorType;
import com.xiniunet.framework.log.LogUtil;
import com.xiniunet.framework.security.Passport;
import net.showcal.tool.Constants;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 食物图片zip上传
 */
public class FoodFileUpload {
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private BufferedRequestContext brc;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FoundationService foundationService;

    public void execute(@Param("File") FileItem fileItem,
                        @Param("Type") UploadTypeEnum type) throws Exception {
        BaseResponse baseResponse = new BaseResponse();
        try {
            if (fileItem == null) {
                return;
            }
            // 必须关闭buffering，未完成的页面才会被显示在浏览器上。
            brc.setBuffering(false);
            if(type==null){
                type = UploadTypeEnum.ITEM;
            }
            // 设置content type，但不需要设置charset，框架会设置正确的charset。
            response.setContentType("text/plain");
            Passport passport = (Passport) request.getAttribute("passport");
            if(passport==null){
                passport = new Passport();
                passport.setUserId(100001L);
            } else{
                if(passport.getUserId()==null){
                    passport.setUserId(100001L);
                }
            }
            //解压
            ZipInputStream zin = new ZipInputStream(fileItem.getInputStream());
            BufferedInputStream bin=new BufferedInputStream(zin);
            ZipEntry entry ;
            while((entry = zin.getNextEntry())!=null){
                if(entry.isDirectory()){
                    continue;
                }
                String fileName = entry.getName();
                fileName = fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());

                byte[] buffer = new byte[(int)entry.getSize()];
                bin.read(buffer);
                FoodFileUploadRequest req = new FoodFileUploadRequest();
                req.setFileStream(buffer);
                req.setFileName(fileName);
                baseResponse = foundationService.uploadFoodFile(req, passport);
            }
            bin.close();
            zin.close();
        } catch (Exception e) {
            baseResponse.addError(ErrorType.SYSTEM_ERROR, Constants.ERROR_MESSAGE_500);
            baseResponse.addError(ErrorType.STACK_DUMP, LogUtil.dumpException(e));
        }finally {
            String json = JSON.toJSONString(baseResponse);
            PrintWriter out = response.getWriter();
            out.println(json);
        }

    }
}
